package com.epoch.platform.sys.job.controller;

import java.math.BigDecimal;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.util.AjaxResult;
import com.epoch.platform.sys.job.dao.SysScheduleJob;
import com.epoch.platform.sys.role.dao.SysRole;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/job")
public class SysScheduleJobController extends BaseController {

	/**
	 * 跳转到选项卡页面
	 */
	public void index() {
		render("/sys/job/sys_job_tab.html");
	}

	/**
	 * 跳转到列表页面
	 */
	public void listUI() {
		render("/sys/job/sys_job_list.html");
	}

	public void findJobListAjax() {
		Kv param = commonParams();
		SqlPara sqlPara = Db.getSqlPara("systemManage.findSysScheduleJob", param);
		Page<SysRole> roleList = SysRole.dao.paginate(sqlPara, param);
		renderJson(roleList);
	}

	public void suvUI() {
		String id = getPara("ID");
		SysScheduleJob scheduleJob = null;
		if (StringUtils.isNotBlank(id)) {
			scheduleJob = SysScheduleJob.dao.findById(id);
		}

		setAttr("scheduleJob", scheduleJob);
		render("/sys/job/sys_job_edit.html");
	}

	public void save() {
		try {
			SysScheduleJob scheduleJob = getModel(SysScheduleJob.class, "scheduleJob");
			AjaxResult ajaxResult = new AjaxResult();
			if (scheduleJob != null) {
				if (scheduleJob.saveOrUpdate()) {
					renderJson(ajaxResult.success(null));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delete() {
		String[] ids = getParaValues("ids[]");
		if (ArrayUtils.isNotEmpty(ids)) {
			for (String id : ids) {
				try {
					SysScheduleJob.dao.deleteById(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		renderNull();
	}

	// 校验任务名称是否重复
	public void checkJobName() {
		String id = getPara("id");
		String jobName = getPara("jobName");
		String msg = "true";
		Record record = new Record();
		if (id != null && id != "") {
			record = Db.findFirst(
					"SELECT COUNT(*) FROM SYS_SCHEDULE_JOB WHERE JOB_NAME = '" + jobName + "'AND ID != '" + id + "'");
		} else {
			record = Db.findFirst("SELECT COUNT(*) FROM SYS_SCHEDULE_JOB WHERE JOB_NAME = '" + jobName + "'");
		}
		Integer count = record.getInt("count(*)");
		if (count > 0) {
			msg = "false";
		}
		renderText(msg);
	}

}
